package com.jf.docsify.common.utils;

import java.util.Date;

import org.apache.commons.lang3.StringUtils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.jf.docsify.modules.model.SysUser;

/**
 * Description: token 工具类
 *
 * @author chenwr
 * @version 1.0
 *
 * <pre>
 * 修改记录:
 * 修改后版本           修改人       修改日期         修改内容
 * 2022/7/26.1       chenwr    2022/7/26           Create
 * </pre>
 * @date 2022/7/26
 */
public class TokenUtil {

    private static int JWT_EXPIRE_MIN = 720; //JWT失效时间 单位：分钟
    private static String JWT_SECRET = "jf-docsify-token"; //JWT秘钥
    public static String TOKEN_USER_ID_PRE_KEY = "TOKEN_USER_ID_";
    private static String USER_TOKEN_PRE_KEY = "USER_TOKEN_";

    /**
     * 生成jwt token
     *
     * @param userId
     * @return
     */
    public static String createJwtToken(String userId) {
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);//签发时间精度:毫秒
        Date expireTime = DateUtils.getAfterMinDate(JWT_EXPIRE_MIN);
        try {
            Algorithm algorithm = Algorithm.HMAC256(JWT_SECRET);
            return JWT.create().withIssuer(userId).withIssuedAt(now).withExpiresAt(expireTime).sign(algorithm);
        } catch (JWTCreationException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 校验token是否有效
     *
     * @param userId
     * @param token
     * @return
     */
    public static boolean validateToken(String userId, String token) {
        boolean active = true;
        try {
            Algorithm algorithm = Algorithm.HMAC256(JWT_SECRET);//声明签名所用的算法和秘钥
            JWTVerifier verifier = JWT.require(algorithm).withIssuer(userId).build();
            verifier.verify(token);
        } catch (TokenExpiredException exception) {
            //System.out.println("--- token 过期");
            active = false;
        } catch (JWTDecodeException exception) {
            //System.out.println("--- token 无效");
            active = false;
        } catch (JWTVerificationException exception) {
            //System.out.println("--- token 错误");
            active = false;
        }
        return active;
    }

    /**
     * 生成token信息
     *
     * @param user
     * @return
     */
    public static String generateTokenInfo(String token, SysUser user) {
        Integer userId = user.getId();
        String oldToken = CacheUtil.AUTHORIZATION.get(TOKEN_USER_ID_PRE_KEY + userId);
        if (StringUtils.isNotBlank(oldToken)) {
            CacheUtil.AUTHORIZATION.remove(TOKEN_USER_ID_PRE_KEY + userId);
            CacheUtil.AUTH_USER.remove(USER_TOKEN_PRE_KEY + oldToken);
        }
        CacheUtil.AUTHORIZATION.put(TOKEN_USER_ID_PRE_KEY + userId, token);
        CacheUtil.AUTH_USER.put(USER_TOKEN_PRE_KEY + token, user);
        return token;
    }

    public static SysUser getUser(String token) {
        return CacheUtil.AUTH_USER.get(USER_TOKEN_PRE_KEY+token);
    }

    public static String getToken(String userId) {
        return CacheUtil.AUTHORIZATION.get(TOKEN_USER_ID_PRE_KEY + userId);
    }

    public static void removeToken(String userId) {
        String token = CacheUtil.AUTHORIZATION.get(TOKEN_USER_ID_PRE_KEY + userId);
        CacheUtil.AUTHORIZATION.remove(TOKEN_USER_ID_PRE_KEY + userId);
        CacheUtil.AUTH_USER.remove(USER_TOKEN_PRE_KEY + token);
    }
}